from mcp.server.fastmcp import FastMCP, Context
import asyncio
from mcp.server.session import ServerSession
from pydantic import BaseModel, Field, field_validator

mcp = FastMCP(name="Completions Server")


class TaskInfo(BaseModel):
    title: str = Field(description="任务标题")
    priority: str = Field(description="任务优先级(low/medium/high)")

    @field_validator("priority")
    def validate_priority(cls, v):
        if v.lower() not in ["low", "medium", "high"]:
            raise ValueError("优先级必须是low medium或high")
        return v.lower()


class UserPreference(BaseModel):
    checkAlternative: bool = Field(description="是否提供替代选择")
    alternativeOption: str = Field(default="option", description="替代选择的名称")


class ConfirmationData(BaseModel):
    proceed: bool = Field(description="是否继续执行")
    reason: str = Field(default="", description="继续或取消的原因(可选)")


@mcp.tool()
async def create_task(ctx: Context[ServerSession, None]) -> str:
    try:
        result = await ctx.elicit(message="请提供任务信息", schema=TaskInfo)
        if result.action == "accept" and result.data:
            task_info = result.data
            return f"任务创建成功:{task_info.title},优先级{task_info.priority}"
        elif result.action == "decline":
            return "用户拒绝了任务创建的请求"
        else:
            return "任务创建取消"

    except Exception as e:
        return f"创建任务失败:{str(e)}"


@mcp.tool()
async def collect_preference(ctx: Context[ServerSession, None]) -> str:
    try:
        result = await ctx.elicit(message="请告诉我你的偏好设置", schema=UserPreference)
        if result.action == "accept" and result.data:
            preference = result.data
            return f"偏好设置已经收集:是否提供替代选择:{preference.checkAlternative},替代选择:{preference.alternativeOption}"
        elif result.action == "decline":
            return "用户拒绝了偏好设置"
        else:
            return "偏好设置取消"
    except Exception as e:
        return f"偏好设置失败:{str(e)}"


@mcp.tool()
async def confirm_action(ctx: Context[ServerSession, None]) -> str:
    try:
        result = await ctx.elicit(
            message="这是一个非常重要的操作，请确认是否继续", schema=ConfirmationData
        )
        if result.action == "accept" and result.data:
            confirmation = result.data
            return f"是否继续执行:{confirmation.proceed},替代选择的名称:{confirmation.reason}"
        elif result.action == "decline":
            return "用户拒绝了确认操作"
        else:
            return "确认操作取消"
    except Exception as e:
        return f"确认操作失败:{str(e)}"


async def main():
    # 启动服务器
    # 可用工具
    #   create_task创建任务
    #   collect_preferences 收集用户偏好
    #   confirm_action确认操作
    mcp.run(transport="stdio")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("服务器已经停止")
    except Exception as e:
        print("服务器启动失败")
